<template>
  <Row :gutter="10" style="align-items: center">
    <Col :span="4">
      <Select v-model:value="type" style="width: 100%">
        <Select.Option value="">全部</Select.Option>
        <Select.Option value="iworkflow/portal_web">iWorkflow</Select.Option>
        <Select.Option value="/wfmobile/mobile">iWorkflow移动端</Select.Option>
        <Select.Option value="wfapi/api">Web Api接口</Select.Option>
        <Select.Option value="dashboard">Dashboard</Select.Option>
        <Select.Option value="none">None</Select.Option>
      </Select>
    </Col>
    <Col :span="4">
      <Input v-model:value="version" allowClear placeholder="请输入过滤的版本" />
    </Col>
    <Col :span="4">
      <Switch v-model:checked="removeImage">
        <template #unCheckedChildren>查询</template>
        <template #checkedChildren>删除</template>
      </Switch>

      <Switch v-if="removeImage" v-model:checked="forceRemove" style="margin-left: 10px">
        <template #unCheckedChildren>普通删除</template>
        <template #checkedChildren>强制删除</template>
      </Switch>
    </Col>
    <Col>
      <Button :type="'primary'" shape="round" @click="execute"><SendOutlined /> 执行</Button>
    </Col>
  </Row>
  <div class="shell" style="margin-top: 5px">
    <p ref="codeEl" @click="copy" class="code" v-html="replaceWhitespace(imageCommand)"></p>
    <p v-html="replaceWhitespace(header)"></p>
  </div>
  <div class="shell details" :style="{ maxHeight: maxHeight - 100 + 'px' }">
    <p v-for="img of details" v-html="replaceWhitespace(img)"></p>
  </div>
</template>
<script setup>
  import { ref, inject, computed, onMounted } from 'vue';
  import { Row, Col, Input, Select, Button, Switch } from 'ant-design-vue';
  import { SendOutlined } from '@ant-design/icons-vue';

  import { replaceWhitespace } from '@/libs/helpers';

  const props = defineProps({
    maxHeight: String | Number
  });

  const $http = inject('$http');
  const $modal = inject('$modal');
  const $message = inject('$message');
  const $copyText = inject('$copyText');

  const codeEl = ref();
  const type = ref('');
  const version = ref('');
  const removeImage = ref(false);
  const forceRemove = ref(false);

  const images = ref([]);

  const imageCommand = computed(() => {
    let command = 'docker images | grep -v harbor | grep -v microsoft | grep -v portainer';

    if (type.value) {
      command += ` | grep ${type.value}`;
    }

    if (version.value) {
      command += ` | grep ${version.value}`;
    }

    if (removeImage.value) {
      command = `docker rmi${forceRemove.value ? ' -f' : ''} $(${command} | awk '{print $3}')`;
    }

    return command;
  });

  const header = computed(() => {
    if (images.value && images.value.length > 0) {
      return images.value[0];
    }

    return '';
  });

  const details = computed(() => {
    let rs = [];

    if (images.value && images.value.length > 0) {
      rs = images.value.slice(1, images.value.length);
    }

    rs = rs.sort((x, y) => x - y);

    return rs;
  });

  async function execute() {
    if (removeImage.value) {
      $modal.confirm({
        title: '警告',
        content: '是否确定删除符合条件的镜像？',
        async onOk() {
          await removeImages();
        }
      });
    } else {
      await searchImages();
    }
  }

  async function searchImages() {
    images.value = [];

    let command = {
      command: imageCommand.value
    };

    let res = await $http.post('/api/shell/exec', command);

    res.datas = res.datas || [];

    if (res.datas.length == 0 || (res.datas.length > 0 && res.datas[0].indexOf('REPOSITORY') != 0)) {
      res.datas.unshift('REPOSITORY                                   TAG               IMAGE ID       CREATED          SIZE');
    }

    images.value =
      res.datas.length == 1
        ? res.datas
        : [
            res.datas[0],
            ...res.datas.slice(1, res.datas.length).sort((a, b) => {
              let sort = 0;

              if (a > b) {
                sort = -1;
              } else if (a < b) {
                sort = 1;
              }

              return sort;
            })
          ];
  }

  function copy() {
    $copyText(codeEl.value).then(() => {
      $message.success('复制成功！');
    });
  }

  async function removeImages() {
    images.value = [];

    let command = {
      command: `${imageCommand.value} &> /home/apps_admin/logs/rmi.log; cat /home/apps_admin/logs/rmi.log;`
    };

    let res = await $http.post('/api/shell/exec', command);

    images.value = res.datas;
  }

  onMounted(async () => {
    await searchImages();
  });
</script>
<style lang="less" scoped>
  :deep(.ant-switch) {
    height: 30px;
    line-height: 30px;
    background: #1890ff;

    .ant-switch-handle {
      top: 6px;
      left: 8px;
    }

    .ant-switch-inner {
      padding: 0 8px 0 8px;
    }

    &.ant-switch-checked {
      background: #ff4d4f;

      .ant-switch-handle {
        left: calc(100% - 18px - 8px);
      }
    }
  }
</style>
